//
//  JWSingleSite.m
//  JWBrowser
//
//  Created by Dejun Liu on 14-11-11.
//  Copyright (c) 2014年 JW. All rights reserved.
//

#import "NetworkService.h"
#import <AFNetworking/AFURLResponseSerialization.h>

@implementation NetworkService

+ (instancetype)sharedInstance
{
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (AFURLSessionManager *)sessionClient
{
    if (!_sessionClient) {
        _sessionClient = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        _sessionClient.responseSerializer = [AFHTTPResponseSerializer serializer];
    }
    return _sessionClient;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _manager = [AFHTTPRequestOperationManager manager];
        AFHTTPResponseSerializer *serializer = [AFHTTPResponseSerializer serializer];
        serializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"baiduapp/json",@"text/html",@"text/plain",nil];
        _manager.responseSerializer = serializer;
        
        AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
        securityPolicy.allowInvalidCertificates = YES;
        
        _manager.securityPolicy = securityPolicy;
    }
    return self;
}

- (void)getURLString:(NSString *)url params:(NSDictionary *)params jsonResponse:(Complation ) complation
{
    [self.manager GET:[url URLEncodeString] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        complation(responseObject,nil);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        complation(nil,error);
    }];
}

- (void)postURLString:(NSString *)url params:(NSDictionary *)prarams jsonResponse:(Complation) complation
{
    [self.manager POST:[url URLEncodeString] parameters:prarams success:^(AFHTTPRequestOperation *operation, id responseData) {
        complation(responseData,nil);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        complation(nil,error);
    }];
}

- (void)uploadData:(NSData *) data key:(NSString *)key apiURL:(NSString *)url completion:(Complation) completion
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params hs_setSafeValue:data forKey:key];
    [self uploadMultiKeyValue:params apiURL:url completion:completion];
}

- (void)uploadFileWithPath:(NSString *) path key:(NSString *)key apiURL:(NSString *)url completion:(Complation) completion
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params hs_setSafeValue:path forKey:key];
    [self uploadMultiKeyValue:params apiURL:url completion:completion];
}


/**
 *  key－>value形式
 *  key服务器接受需要传入的key
 *  value上传资源类型；可以是一个文件路径，也可以是一个二进制文件
 *  @param dic 传入的参数
 */
- (void)uploadMultiKeyValue:(NSDictionary *)dic apiURL:(NSString *)url completion:(Complation) completion
{
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [dic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            if ([obj isKindOfClass:[NSData class]]) {
                NSData *data = obj;
                [formData appendPartWithFileData:obj name:key fileName:@"photo.jpg" mimeType:[data getImeiType]];
            }else if([obj isKindOfClass:[NSString class]])
            {
                NSString *fullPath = obj;
                NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:fullPath]];
                NSString *fileName = [fullPath componentsSeparatedByString:@"/"].lastObject;
                [formData appendPartWithFileURL:[NSURL fileURLWithPath:obj] name:key fileName:fileName mimeType:[data getImeiType] error:nil];
            }
        }];
    } error:nil];
    NSProgress *progress = nil;
    NSURLSessionUploadTask *uploadTask = [self.sessionClient uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if(responseObject)responseObject = [responseObject jsonSerializtion];
        completion(responseObject,error);
    }];
    
    [uploadTask resume];
}

- (void)postDataString:(NSString *)dataString urlString:(NSString *)urlString jsonResponse:(Complation) complation
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [request setTimeoutInterval:30];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    request.HTTPBody=[dataString dataUsingEncoding:NSUTF8StringEncoding];
    
    AFHTTPRequestOperation* operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [responseObject jsonSerializtion];
        complation(dic,nil);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        if (error.code != NSURLErrorTimedOut) {
            complation(nil,error);
        }
        
    }];
    
    [operation start];
}

@end
